﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ultimus.WFServer;
using H2.NET.Common;
using H2.NET.Web.Workflow.Helpers;

namespace H2.NET.Web.Workflow
{
    public partial class Initiate : DwzCode.BasePage
    {
        private DataTable dt = new DataTable();
        public int count = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                load_gv_initiate_list();

                //第一次加载页面时初始化
                if (!Page.IsPostBack)
                {
                    //查询并对列表进行数据绑定
                    load_drp_control_list();
                }
            }
            catch (Exception ex)
            {
                //TaskDB.Log("", false, "调用 initiate.aspx 页面 Page_Load 事件出错：" + ex.Message);
            }
        }


        #region 获取我可以发起的流程
        public DataTable get_all_initiates()
        {

            try
            {
                string strSQL = "";
                string strInitiator = "";
                string strJobFunction = "";
                string strDepartments = "";
                string strGroups = "";
                string strUserName = clsCmm.comm_username;
                string strSummary = txtSummary.Text.Trim();

                //查询过滤中Process下拉列表中的值
                string strProcess = "all";
                if (drpProcess.SelectedItem != null)
                {
                    strProcess = drpProcess.SelectedItem.Value.Trim();
                }

                //string strStep = "all";
                //if (drpStep.SelectedItem != null)
                //{
                //    strStep = drpStep.SelectedItem.Value.Trim();
                //}

                //取得所有的职位、以及根据所有职位查找所属部门
                DataTable dt = new DataTable();

                #region 取得所有的职位、以及根据所有职位查找所属部门

                strSQL += "select distinct rtrim(departments.name) as initiator1,rtrim('\\') as initiator2, rtrim(jobs.jobfunction) as initiator3, '1' as types";
                strSQL += "  from jobs WITH (NOLOCK) ";
                strSQL += " inner join departments WITH (NOLOCK)  on jobs.deptid = departments.id";
                strSQL += " where (lower(jobs.name) = lower('" + strUserName + "') and jobtype in (2, 4, 64))";
                strSQL += "    or jobs.id in (select supervisorid from jobs where lower(name) = lower('" + strUserName + "') and jobtype = 64) ";
                strSQL += " union all ";

                strSQL += "select distinct rtrim(b.name) as initiator1, rtrim('*') as initiator2, rtrim(a.jobfunction) as initiator3, '3' as types";
                strSQL += "  from jobs a WITH (NOLOCK) , departments b WITH (NOLOCK) , (select distinct jobs.supervisorid";
                strSQL += " from jobs WITH (NOLOCK) ";
                strSQL += " where (lower(jobs.name) = lower('" + strUserName + "') and jobtype in (2, 4, 64))";
                strSQL += " or jobs.id in (select supervisorid";
                strSQL += " from jobs WITH (NOLOCK)";
                strSQL += " where lower(name) = lower('" + strUserName + "')";
                strSQL += " and jobtype = 64)) c";
                strSQL += " where a.deptid=b.id and a.id=c.supervisorid";

                strSQL += " union all ";
                strSQL += "select distinct rtrim(a.name) as initiator1, rtrim('') as initiator2, rtrim('') as initiator3, '2' as types";
                strSQL += "  from departments a WITH (NOLOCK) ,";
                strSQL += "       (select deptid";
                strSQL += "          from jobs WITH (NOLOCK) ";
                strSQL += "         inner join departments WITH (NOLOCK) on jobs.deptid = departments.id";
                strSQL += "         where (lower(jobs.name) = lower('" + strUserName + "') and jobtype in (2, 4, 64))";
                strSQL += "            or jobs.id in";
                strSQL += "               (select supervisorid";
                strSQL += "                  from jobs WITH (NOLOCK) ";
                strSQL += "                 where lower(name) = lower('" + strUserName + "')";
                strSQL += "                   and jobtype = 64)) b";
                strSQL += " where a.id = b.deptid";

                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strInitiator += ",'" + dt.Rows[i]["initiator1"].ToString().Trim() + dt.Rows[i]["initiator2"].ToString().Trim() + dt.Rows[i]["initiator3"].ToString().Trim() + "'";
                    if (dt.Rows[i]["types"].ToString().Trim() == "1")
                    {

                        strJobFunction += ",'" + dt.Rows[i]["initiator1"].ToString().Trim() + dt.Rows[i]["initiator2"].ToString().Trim() + dt.Rows[i]["initiator3"].ToString().Trim() + "'";
                    }

                    if (dt.Rows[i]["types"].ToString().Trim() == "2")
                    {
                        strDepartments += ",'" + dt.Rows[i]["initiator1"].ToString().Trim() + dt.Rows[i]["initiator2"].ToString().Trim() + dt.Rows[i]["initiator3"].ToString().Trim() + "'";
                    }
                }

                #endregion

                #region 根据所有职位查找所属工作组
                
                strSQL = "";
                strSQL += "select distinct groups.gname as initiator";
                strSQL += "   from groups WITH (NOLOCK) ";
                strSQL += "  where groups.member in (''" + strInitiator.Replace(@"\", @"*") + ") ";
                strSQL += "     or lower(groups.member) =lower('" + strUserName + "') ";
                strSQL += " union all ";
                strSQL += " select distinct groups.gname as initiator";
                strSQL += "   from groups WITH (NOLOCK) ";
                strSQL += "  where groups.member in (select groups.gname";
                strSQL += "                            from groups";
                strSQL += "                           where groups.member in (''" + strInitiator.Replace(@"\", @"*") + ")";
                strSQL += "                             and membertype = 2)";

                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    strGroups += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                }

                #endregion

                #region 根据用户、职位、部门、工作组查找发起箱列表
                
                strSQL = "";
                strSQL += "select  rtrim(z.description)     as summary";
                //中文的情况，流程名变化
                if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
                {
                    strSQL += " ,a.processhelpurl as processname";
                }
                else
                {
                    strSQL += " ,a.processname";
                }

                strSQL += " ,rtrim(b.description) as processno";
                strSQL += " ,rtrim(a.helpurl) as helpurl";
                strSQL += " ,'' as openform";
                strSQL += " ,rtrim(a.steplabel) as steplabel";
                strSQL += " ,rtrim(a.processversion)  as processversion";
                strSQL += " ,rtrim(a.initiateid) as taskid";
                strSQL += " ,b.status as status";
                strSQL += " ,'' as img_status";
                strSQL += "  from initiate a WITH (NOLOCK) ";
                strSQL += "  INNER JOIN bpmsystem AS Z WITH (NOLOCK) ON a.processname = z.processname";
                strSQL += " inner join processes b WITH (NOLOCK) on (a.processname = b.processname and a.processversion = b.processversion AND RTRIM(LTRIM(B.description)) IN (SELECT KeyWords FROM BPMSYSTEM WHERE Platform = '" + Util.AppSettings("platform") + "'))";
                strSQL += " where ((a.initiatortype = 1 and lower(a.initiator) = lower('" + strUserName + "'))";
                strSQL += " or (a.initiatortype = 4 and a.initiator in (''" + strGroups + ")) ";
                strSQL += " or (a.initiatortype = 8 and a.initiator in (''" + strDepartments + "))";
                strSQL += " or (a.initiatortype = 2 and a.initiator in (''" + strJobFunction + ")))";

                //added by zk 2009-08-28 start 模板功能
                //strSQL += "    and a.description is null";
                //added by zk 2009-08-28 end



                //如果是点击了删除的情况
                //if (e_element_tr_delete_template.Value == "block")
                //{
                //    strSQL += "   and a.description is not null";
                //    strSQL += "   and a.initiateid not in(select taskid from taskqueue WITH (NOLOCK))";
                //}

                //查询过滤
                if (strProcess != "all")
                {
                    strSQL = strSQL + " and a.processname = '" + strProcess + "'";
                }

                //if (strStep != "all")
                //{
                //    strSQL = strSQL + " and a.steplabel = '" + strStep + "'";
                //}

                if (strSummary != "")
                {
                    strSQL = strSQL + " and a.description like '%" + strSummary + "%'";
                }

                strSQL += " and b.description not like '%SMD%'";
                //strSQL = strSQL + " order by a.processname";



                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);

                #endregion

                return dt;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 initiate.aspx 页面 getInitiate 方法出错：" + ee.Message);
                return null;
            }
        }
        #endregion

        #region 查询并对列表进行数据绑定
        public void load_gv_initiate_list()
        {
            try
            {
                //版本名称转换
                bool Flg = false;
                string[] strVersion = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

                //加载列表
                dt = get_all_initiates();

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();
                    dt.Rows[i]["openform"] = UltimusHelper.ResolveUrl(dt.Rows[i]["helpurl"].ToString(), 
                                                                    dt.Rows[i]["taskid"].ToString(), 
                                                                    dt.Rows[i]["processname"].ToString());

                    //如果是流程被停用的情况                    
                    dt.Rows[i]["img_status"] = UltimusHelper.ResolveStatusImg(dt.Rows[i]["status"].ToString().Trim());

                    //如果在描述不为空的情况，则为模板对应的图标
                    if (dt.Rows[i]["summary"] != DBNull.Value && dt.Rows[i]["summary"].ToString().Trim() != "")
                    {
                        dt.Rows[i]["img_status"] = "frm_initiate_templete.gif";
                        Flg = true;
                    }

                    //版本名称转换
                    if (dt.Rows[i]["processversion"] != DBNull.Value && System.Convert.ToInt16(dt.Rows[i]["processversion"]) <= 26)
                    {
                        dt.Rows[i]["processversion"] = strVersion[System.Convert.ToInt16(dt.Rows[i]["processversion"]) - 1];
                    }
                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "processno ASC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                gvInitiate.DataSource = dt;
                gvInitiate.DataBind();

                count = dt.Rows.Count;

                //如果存在模板的情况，显示删除按钮
                //if (Flg)
                //{
                //    img_delete.Visible = true;
                //    lblDelete.Visible = true;
                //    if (e_element_tr_delete_template.Value == "block")
                //    {
                //        btnDelete.Visible = true;
                //    }
                //    else
                //    {
                //        btnDelete.Visible = false;
                //    }
                //}
                //else
                //{
                //    img_delete.Visible = false;
                //    lblDelete.Visible = false;
                //}

                #region 导航栏初始化

                //获取Label实例，显示页次信息
                //int rowCount = dt.Rows.Count;

                //Label lblCurrent = this.lblPageCurrent;
                //Label lblCount = this.lblPageCount;
                //Label lblRow = this.lblPageRow;
                ////获取按钮实例，为了控制其是否可用
                //LinkButton btnFirstTem = this.btnFirst;
                //LinkButton btnPrevTem = this.btnPrev;
                //LinkButton btnNextTem = this.btnNext;
                //LinkButton btnLastTem = this.btnLast;

                //if (lblCurrent != null)
                //    lblCurrent.Text = (this.gvInitiate.PageIndex + 1).ToString();
                //if (lblCount != null)
                //{
                //    if (this.gvInitiate.PageCount.ToString() != "0" && this.gvInitiate.PageCount.ToString() != "")
                //        lblCount.Text = this.gvInitiate.PageCount.ToString();
                //    else
                //        lblCount.Text = (this.gvInitiate.PageCount + 1).ToString();
                //}
                //if (lblRow != null)
                //{
                //    lblRow.Text = rowCount.ToString();
                //}

                ////只有一页，所有分页按钮不可用
                //if (this.gvInitiate.PageCount <= 1)
                //{
                //    btnFirstTem.Visible = false;
                //    btnPrevTem.Visible = false;
                //    btnNextTem.Visible = false;
                //    btnLastTem.Visible = false;
                //    btnGoTo.Visible = false;
                //    drpGoTo.Visible = false;
                //}
                //else
                //{
                //    //加载 GoTo 下拉框
                //    btnGoTo.Visible = true;
                //    drpGoTo.Visible = true;
                //    drpGoTo.Items.Clear();
                //    for (int i = 0; i < this.gvInitiate.PageCount; i++)
                //    {
                //        drpGoTo.Items.Add((i + 1).ToString());
                //    }

                //    drpGoTo.SelectedIndex = this.gvInitiate.PageIndex;

                //    if (this.gvInitiate.PageIndex == 0)
                //    {
                //        btnFirstTem.Enabled = false;
                //        btnPrevTem.Enabled = false;
                //        btnNextTem.Enabled = true;
                //        btnLastTem.Enabled = true;
                //    }
                //    else if (this.gvInitiate.PageIndex == (this.gvInitiate.PageCount - 1))
                //    {
                //        btnFirstTem.Enabled = true;
                //        btnPrevTem.Enabled = true;
                //        btnNextTem.Enabled = false;
                //        btnLastTem.Enabled = false;
                //    }
                //    else
                //    {
                //        btnFirstTem.Enabled = true;
                //        btnPrevTem.Enabled = true;
                //        btnNextTem.Enabled = true;
                //        btnLastTem.Enabled = true;
                //    }
                //}
                #endregion

            }
            catch (Exception ee)
            {
                //TaskDB.Log("", false, "调用 initiate.aspx 页面 load_gv_initiate_list方法出错：" + ee.Message);
            }
        }
        #endregion

        #region 查询并对查询下拉列表进行填充
        public void load_drp_control_list()
        {
            try
            {
                //清空现有列表
                drpProcess.Items.Clear();
                //drpStep.Items.Clear();

                //增加第一行
                drpProcess.Items.Add(new ListItem("All", "all"));

                //循环所有的记录集
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    bool Flg = true;

                    //流程名称下拉列表
                    foreach (ListItem item in drpProcess.Items)
                    {
                        if (dt.Rows[i]["processname"].ToString() == item.Value)
                        {
                            Flg = false;
                            break;
                        }
                    }

                    ////步骤名称下拉列表
                    //foreach (ListItem item in drpStep.Items)
                    //{
                    //    if (dt.Rows[i]["steplabel"].ToString() == item.Value)
                    //    {
                    //        Flg2 = false;
                    //        break;
                    //    }
                    //}

                    //如果不存在的情况
                    if (Flg)
                    {
                        drpProcess.Items.Add(new ListItem(GetCache(dt.Rows[i]["processname"].ToString().Trim()), dt.Rows[i]["processname"].ToString()));
                    }

                    //if (Flg2)
                    //{
                    //    drpStep.Items.Add(new ListItem(dt.Rows[i]["steplabel"].ToString(), dt.Rows[i]["steplabel"].ToString()));
                    //}
                }
            }
            catch (Exception ee)
            {
                //TaskDB.Log("", false, "调用 initiate.aspx 页面 load_drp_control_list方法出错：" + ee.Message);
            }
        }
        #endregion

    }
}
